import { useUserStore } from '@/stores/user'

// 基础配置
const config = {
  baseUrl: 'https://strarry.top/api'
  // baseUrl: 'http://localhost:8080'
}

// 是否正在刷新token
let isRefreshing = false
// 重试队列
let requests = []

// 刷新token
const refreshToken = async () => {
  const userStore = useUserStore()
  try {
    const res = await uni.request({
      url: config.baseUrl + '/refreshToken',
      method: 'POST',
      data: {
        refreshToken: userStore.refreshToken
      }
    })
    if (res.statusCode === 200 && res.data.data.accessToken) {
      userStore.updateToken(res.data.data.accessToken, res.data.data.refreshToken)
      return true
    }
  } catch (e) {
    userStore.logout()
    uni.reLaunch({ url: '/pages/login/login' })
  }
  return false
}

// 基础请求方法
const request = async (options = {}) => {
  const userStore = useUserStore()
  
  // 请求拦截 - 确保不重复拼接baseUrl
  if (!options.url.startsWith('http')) {
    options.url = config.baseUrl + options.url
  }
  if (userStore.accessToken) {
    options.header = options.header || {}
    options.header['Authorization'] = `${userStore.accessToken}`
  }

  try {
    const res = await uni.request(options)
    
    // 响应拦截
    if (res.statusCode === 200) {
      return res.data
    } else if (res.statusCode === 401) {
      if (!isRefreshing) {
        isRefreshing = true
        const success = await refreshToken()
        isRefreshing = false
        if (success) {
          // 更新请求头
          options.header = options.header || {}
          options.header['Authorization'] = `${useUserStore().accessToken}`
          // 重试请求
          return request(options)
        } else {
          throw new Error('刷新token失败')
        }
      } else {
        // 直接返回错误，避免队列堆积
        throw new Error('等待token刷新中')
      }
    }
    
    uni.showToast({
      title: res.data?.message || '请求失败',
      icon: 'none'
    })
    throw res
  } catch (err) {
    uni.showToast({
      title: err.errMsg || '网络错误',
      icon: 'none'
    })
    throw err
  }
}

export default request
